package org.subatu.orm.query.table;


import org.subatu.orm.query.base.OrderEnum;
import org.subatu.orm.util.ChkUtil;

/**
 * 查询列
 */
public class QueryColumn {

    // 列名称
    private String column;

    // 别名
    private String alias;

    // 所在表
    private TableDef table;

    // 函数包裹:例如 count(*)
    private String sqlFunc;

    public QueryColumn(String column) {
        this.column = column;
    }

    public QueryColumn(String column, String tableName) {
        this.column = column;
        this.table = new TableDef(tableName);
    }

    // 设置别名
    public QueryColumn as(String alias) {
        this.alias = alias;
        return this;
    }

    public QueryColumn count() {
        this.sqlFunc = "count";
        return this;
    }

    public QueryColumn max() {
        this.sqlFunc = "max";
        return this;
    }

    public QueryColumn distinct() {
        this.sqlFunc = "distinct";
        return this;
    }

    // 设置函数
    public QueryColumn sqlFunc(String sqlFunc) {
        this.sqlFunc = sqlFunc;
        return this;
    }

    // 编译查询sql
    public String buildSql(String tableAlias) {
        String sql = tableAlias != null ? tableAlias + "." : "";
        sql += this.column;
        if (ChkUtil.isNotNull(sqlFunc)) {
            sql = sqlFunc + "(" + sql + ")";
        }
        sql += ChkUtil.isNotNull(alias) ? " as " + alias : "";
        sql += ",";
        return sql;
    }

    // 编译条件sql
    public String buildCondSql(String tableAlias) {
        String sql = tableAlias != null ? tableAlias + "." : "";
        sql += this.column;
        if (ChkUtil.isNotNull(sqlFunc)) {
            sql = sqlFunc + "(" + sql + ")";
        }
        return sql;
    }

    // 编译排序sql
    public String buildOrderBySql(String tableAlias, OrderEnum orderEnum) {
        String sql = tableAlias != null ? tableAlias + "." : "";
        sql += this.column + ' ';
        sql += orderEnum.getValue();
        sql += ",";
        return sql;
    }

    // --------------------------- get / set ---------------------------------


    public TableDef getTable() {
        return table;
    }
}
